package com.qys.livesMall.shop.scheduledTask;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qys.livesMall.shop.modal.entity.SeckillActivity;
import com.qys.livesMall.shop.service.SeckillActivityService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @packageName:
 * @className:OrderRunner
 * @Description:
 * @author:guomx
 * @date:2023/7/2215:42
 */
@Component
public class OrderRunner implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(OrderRunner.class);
    @Resource
    TimeWheelRunner timeWheelRunner;
    @Resource
    SeckillActivityService seckillActivityService;
    @Override
    public void run(String... args) throws Exception {
        try {
            querySeckillActivity();
        }catch (Exception e){
            log.error("Error running OrderRunner:{}",e.getMessage());
        }
    }

    private void querySeckillActivity(){
        LambdaQueryWrapper<SeckillActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(SeckillActivity::getStartTime,System.currentTimeMillis());
        List<SeckillActivity> ativity = seckillActivityService.list(wrapper);
        for (SeckillActivity seckillActivity : ativity) {
            if (seckillActivity.getAppointment()!=0){
                long appointment = TimeUnit.MINUTES.toMillis(seckillActivity.getAppointment());
                long time = seckillActivity.getStartTime() - appointment;
                Duration delay = Duration.ofSeconds(time-System.currentTimeMillis()/1000);
                timeWheelRunner.scheduleSeckillCancellation(delay);
            }
        }
    }
}
